package com.boc.langxiang.ui.fragment.shop;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.slip.SwipeViewPager;
import com.boc.langxiang.R;
import com.boc.langxiang.contract.shop.ShopIndexContract;
import com.boc.langxiang.entity.bean.GoodsBean;
import com.boc.langxiang.entity.bean.MultipleItem;
import com.boc.langxiang.entity.bean.PhotoBean;
import com.boc.langxiang.entity.bean.ShopBannerInfo;
import com.boc.langxiang.entity.response.BaseResponse;
import com.boc.langxiang.entity.response.ShopGoodsContent;
import com.boc.langxiang.entity.response.ShoppingCarNumContent;
import com.boc.langxiang.manager.PicassoImageLoader;
import com.boc.langxiang.manager.UserInfoManager;
import com.boc.langxiang.presenter.shop.ShopIndexPresenter;
import com.boc.langxiang.ui.activity.shop.ProductDetail2Activity;
import com.boc.langxiang.ui.activity.shop.ProductDetailActivity;
import com.boc.langxiang.ui.activity.shop.ProductSearchResultActivity;
import com.boc.langxiang.ui.activity.shop.ProductsAllActivity;
import com.boc.langxiang.ui.activity.shop.ShopGoodsActivity;
import com.boc.langxiang.ui.activity.shop.ShoppingCarActivity;
import com.boc.langxiang.ui.activity.shop.SpecialTopicActivity;
import com.boc.langxiang.ui.activity.shop.SpecialTopicDetailActivity;
import com.boc.langxiang.ui.adapter.ShopBannerPageAdapter;
import com.boc.langxiang.ui.fragment.BaseFragment;
import com.boc.langxiang.util.StringUtil;
import com.boc.langxiang.util.T;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


public class ShopFragment extends BaseFragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, ShopIndexContract.View {

    @BindView(R.id.action_shopping_car)
    RelativeLayout actionShoppingCar;
    @BindView(R.id.search_mag_icon)
    ImageView searchMagIcon;

    SwipeViewPager viewpager;

    TextView jingpinSeeMore;

    RecyclerView jingpinRecyclerView;

    TextView zhuantiSeeMore;

    RecyclerView zhuantiRecyclerView;

    TextView productsSeeMore;

    RecyclerView productsRecyclerView;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.search_edt)
    EditText searchEdt;
    @BindView(R.id.shoppingCar_num)
    TextView shoppingCarNum;

    private View rootView;

    private BaseQuickAdapter<GoodsBean> jingPinAdapter;
    private BaseQuickAdapter<GoodsBean> zhuanTiAdapter;
    private BaseQuickAdapter<GoodsBean> productsAdapter;
    private ShopBannerPageAdapter mBannerPageAdapter;

    private MultiRecyclerAdapter multiRecyclerAdapter;

    private ShopIndexContract.Presenter mPresenter;

    private List<ShopBannerInfo> mBanners;

    private Runnable refreshingRunnable = new Runnable() {
        @Override
        public void run() {
            swipeRefresh.setRefreshing(true);
        }
    };
    private boolean mIsRefresh;

    public static ShopFragment newInstance() {
        ShopFragment fragment = new ShopFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_shop, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        swipeRefresh.setOnRefreshListener(this);
        swipeRefresh.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        initAdapter();

//        viewpager.setAdapter(mBannerPageAdapter);
//
//        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getActivity());
//        linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
//        jingpinRecyclerView.setLayoutManager(linearLayoutManager1);
//
//        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(getActivity());
//        linearLayoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
//        zhuantiRecyclerView.setLayoutManager(linearLayoutManager2);
//
//        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
//        productsRecyclerView.setLayoutManager(gridLayoutManager);
//
//        jingpinRecyclerView.setAdapter(jingPinAdapter);
//        zhuantiRecyclerView.setAdapter(zhuanTiAdapter);
//        productsRecyclerView.setAdapter(productsAdapter);
//
//        jingpinTitle.setTypeface(mTypeFace);
//        zhuantiTitle.setTypeface(mTypeFace);
//        productsTitle.setTypeface(mTypeFace);
//
//
//        productsSeeMore.setOnClickListener(this);
//        zhuantiSeeMore.setOnClickListener(this);


        actionShoppingCar.setOnClickListener(this);

        searchEdt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    if (!StringUtil.isEmpty(searchEdt.getText().toString())) {
                        searchProducts(searchEdt.getText().toString());
                        searchEdt.setText("");
                    }
                }
                return false;
            }
        });

        initData();
    }

    private void searchProducts(String searchWord) {
        Intent intent = new Intent(getActivity(), ProductSearchResultActivity.class);
        intent.putExtra("keyword", searchWord);
        startActivity(intent);
    }

    private void initData() {
        mPresenter = new ShopIndexPresenter(this);
        onRefresh();

    }


    private void initAdapter() {
        mBanners = new ArrayList<>();
        mBannerPageAdapter = new ShopBannerPageAdapter(getActivity(), mBanners);

        jingPinAdapter = new BaseQuickAdapter<GoodsBean>(R.layout.shop_jingxuan_item, null) {
            @Override
            protected void convert(BaseViewHolder helper, final GoodsBean item) {
                if (helper.getLayoutPosition() != 0) {
                    helper.getView(R.id.margin_left).setVisibility(View.GONE);
                } else {
                    helper.getView(R.id.margin_left).setVisibility(View.VISIBLE);
                }
                List<PhotoBean> photo = item.getPhoto();
                if (photo != null && !photo.isEmpty()) {
                    PhotoBean photoBean = photo.get(0);
                    if (photoBean != null) {
                        String url = photoBean.getUrl();
                        if (!StringUtil.isEmpty(url)) {
                            PicassoImageLoader.getInstance().displayUrlImage(mContext, url, (ImageView) helper.getView(R.id.img_iv));
                        }
                    }
                }

                helper.setText(R.id.title_tv, item.getTitle());

                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String designer_status = item.getDesigner_status();
                        switch (designer_status) {
                            case "2":
                                Intent intent = new Intent(mContext, ProductDetailActivity.class);
                                intent.putExtra("id", item.getId());
                                mContext.startActivity(intent);
                                break;
                            case "3":
                                intent = new Intent(mContext, ProductDetail2Activity.class);
                                intent.putExtra("id", item.getId());
                                mContext.startActivity(intent);
                                break;
                        }
                    }
                });
            }
        };

        zhuanTiAdapter = new BaseQuickAdapter<GoodsBean>(R.layout.shop_zhuanti_item, null) {
            @Override
            protected void convert(BaseViewHolder helper, final GoodsBean item) {
                if (helper.getLayoutPosition() != 0) {
                    helper.getView(R.id.margin_left).setVisibility(View.GONE);
                } else {
                    helper.getView(R.id.margin_left).setVisibility(View.VISIBLE);
                }

                if (item.getPhoto() != null && item.getPhoto().size() > 0) {
                    PicassoImageLoader.getInstance().displayUrlImage(mContext, item.getPhoto().get(0).getUrl()
                            , (ImageView) helper.getView(R.id.img_iv));
                }

                helper.setText(R.id.title_tv, item.getTitle());

                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String id = item.getId();
                        Intent intent = new Intent(mContext, SpecialTopicDetailActivity.class);
                        intent.putExtra("id", id);
                        intent.putExtra("title", item.getTitle());
                        intent.putExtra("content", item.getContent());
                        startActivity(intent);
                    }
                });
            }
        };

        productsAdapter = new BaseQuickAdapter<GoodsBean>(R.layout.shop_products_item, null) {
            @Override
            protected void convert(BaseViewHolder helper, final GoodsBean item) {
                List<PhotoBean> photo = item.getPhoto();
                if (photo != null && !photo.isEmpty()) {
                    PhotoBean photoBean = photo.get(0);
                    if (photoBean != null) {
                        String url = photoBean.getUrl();
                        if (!StringUtil.isEmpty(url)) {
                            PicassoImageLoader.getInstance().displayUrlImage(mContext, url, (ImageView) helper.getView(R.id.img_iv));
                        }
                    }
                }

                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String designer_status = item.getDesigner_status();
                        switch (designer_status) {
                            case "2":
                                Intent intent = new Intent(mContext, ProductDetailActivity.class);
                                intent.putExtra("id", item.getId());
                                startActivity(intent);
                                break;
                            case "3":
                                intent = new Intent(mContext, ProductDetail2Activity.class);
                                intent.putExtra("id", item.getId());
                                startActivity(intent);
                                break;
                        }

                    }
                });
            }
        };

        View bannerLayout = getActivity().getLayoutInflater().inflate(R.layout.shop_banner_layout, null);
        viewpager = (SwipeViewPager) bannerLayout.findViewById(R.id.viewpager);
        viewpager.setAdapter(mBannerPageAdapter);
        viewpager.startScorll();

        List<MultipleItem> mutipleItems = new ArrayList<>();

        MultipleItem bannerItem = new MultipleItem();
        bannerItem.setItemType(MultipleItem.banner);
//        mutipleItems.add(bannerItem);

        MultipleItem goodsItem = new MultipleItem();
        goodsItem.setItemType(MultipleItem.goods);
        mutipleItems.add(goodsItem);

        MultipleItem specialTopicItem = new MultipleItem();
        specialTopicItem.setItemType(MultipleItem.specialTopic);
        mutipleItems.add(specialTopicItem);

        MultipleItem productsItem = new MultipleItem();
        productsItem.setItemType(MultipleItem.allProducts);
        mutipleItems.add(productsItem);

        multiRecyclerAdapter = new MultiRecyclerAdapter(getActivity(), mutipleItems);
        multiRecyclerAdapter.addHeaderView(bannerLayout);

        recyclerView.setAdapter(multiRecyclerAdapter);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.products_seeMore:
                intent = new Intent(getActivity(), ProductsAllActivity.class);
                startActivity(intent);
                break;

            case R.id.zhuanti_seeMore:
                intent = new Intent(getActivity(), SpecialTopicActivity.class);
                startActivity(intent);
                break;

            case R.id.action_shopping_car:
                if (isLogin()) {
                    intent = new Intent(getActivity(), ShoppingCarActivity.class);
                    startActivity(intent);
                }
                break;

            case R.id.jingpin_seeMore:
                intent = new Intent(getActivity(), ShopGoodsActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onRefresh() {
        if (mIsRefresh) {
            return;
        }
        mIsRefresh = true;
        mPresenter.star();
    }

    @Override
    public void onGetBannerSuccess(BaseResponse<List<ShopBannerInfo>> response) {
        mIsRefresh = false;
        List<ShopBannerInfo> content = response.getContent();
        if (content == null) {
            return;
        }
        mBanners.clear();
        mBanners.addAll(content);
        mBannerPageAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetGoodsSuccess(BaseResponse<ShopGoodsContent> response) {
        if (response.getContent().getRes() != null) {
            jingPinAdapter.setNewData(response.getContent().getRes());
        }
    }

    @Override
    public void onGetAllProductSuccess(BaseResponse<ShopGoodsContent> response) {
        if (response.getContent().getRes() != null) {
            productsAdapter.setNewData(response.getContent().getRes());
        }
    }

    @Override
    public void onGetSpecialTopicSuccess(BaseResponse<ShopGoodsContent> response) {
        if (response.getContent().getRes() != null) {
            zhuanTiAdapter.setNewData(response.getContent().getRes());
        }
    }

    @Override
    public void onGetShoppingCarNumberSuccess(BaseResponse<ShoppingCarNumContent> response) {
        if (response.getContent().getCartnumber() > 0) {
            shoppingCarNum.setVisibility(View.VISIBLE);
            if (response.getContent().getCartnumber() < 100) {
                shoppingCarNum.setText(String.valueOf(response.getContent().getCartnumber()));
            } else {
                shoppingCarNum.setText("99+");
            }
        } else {
            shoppingCarNum.setVisibility(View.GONE);
        }
    }

    @Override
    public void showLoading() {
        swipeRefresh.post(refreshingRunnable);
    }

    @Override
    public void hideLoading() {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(false);
            }
        });
        mIsRefresh = false;
    }

    @Override
    public void onError(String code, String msg) {
        mIsRefresh = false;
        T.showShort(getActivity(), msg);
    }

    @Override
    public void onResume() {
        if (!StringUtil.isEmpty(UserInfoManager.getInstance().getToken())) {
            mPresenter.getShoppingCarNumber();
        }
        super.onResume();
    }

    private class MultiRecyclerAdapter extends BaseMultiItemQuickAdapter<MultipleItem> {

        /**
         * Same as QuickAdapter#QuickAdapter(Context,int) but with
         * some initialization data.
         *
         * @param context The context.
         * @param data    A new list is created out of this one to avoid mutable list
         */
        public MultiRecyclerAdapter(Context context, List<MultipleItem> data) {
            super(data);
            addItemType(MultipleItem.banner, R.layout.shop_banner_layout);
            addItemType(MultipleItem.goods, R.layout.shop_jingpin_layout);
            addItemType(MultipleItem.specialTopic, R.layout.shop_zhuanti_layout);
            addItemType(MultipleItem.allProducts, R.layout.shop_all_products_layout);
        }

        @Override
        protected void convert(BaseViewHolder helper, MultipleItem item) {
            switch (helper.getItemViewType()) {
                case MultipleItem.banner:
                    viewpager = helper.getView(R.id.viewpager);
                    viewpager.setAdapter(mBannerPageAdapter);
                    viewpager.startScorll();
                    break;
                case MultipleItem.goods:
                    jingpinRecyclerView = helper.getView(R.id.jingpin_recyclerView);
                    jingpinSeeMore = helper.getView(R.id.jingpin_seeMore);
                    jingpinSeeMore.setOnClickListener(ShopFragment.this);

                    LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getActivity());
                    linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
                    jingpinRecyclerView.setLayoutManager(linearLayoutManager1);

                    jingpinRecyclerView.setAdapter(jingPinAdapter);

                    break;

                case MultipleItem.specialTopic:
                    zhuantiRecyclerView = helper.getView(R.id.zhuanti_recyclerView);
                    zhuantiSeeMore = helper.getView(R.id.zhuanti_seeMore);

                    LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(getActivity());
                    linearLayoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
                    zhuantiRecyclerView.setLayoutManager(linearLayoutManager2);

                    zhuantiRecyclerView.setAdapter(zhuanTiAdapter);

                    zhuantiSeeMore.setOnClickListener(ShopFragment.this);
                    break;


                case MultipleItem.allProducts:
                    productsRecyclerView = helper.getView(R.id.products_recyclerView);
                    productsSeeMore = helper.getView(R.id.products_seeMore);

                    GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
                    productsRecyclerView.setLayoutManager(gridLayoutManager);

                    productsRecyclerView.setAdapter(productsAdapter);

                    productsSeeMore.setOnClickListener(ShopFragment.this);
                    break;
            }

        }
    }
}